package com.jzx.provider.ucenter.consul.service;

import com.aliyun.oss.model.ObjectMetadata;
import com.google.common.collect.ImmutableMap;
import com.jzx.provider.common.constants.Expire;
import com.jzx.provider.common.constants.PlatForm;
import com.jzx.provider.common.constants.Status;
import com.jzx.provider.common.service.FileService;
import com.jzx.provider.common.utils.CodeUtil;
import com.jzx.provider.common.utils.JwtUtil;
import com.jzx.provider.exception.MyErrorType;
import com.jzx.provider.exception.UcenterRuntimeException;
import com.jzx.provider.ucenter.consul.dto.command.*;
import com.jzx.provider.ucenter.consul.dto.result.ConsulResult;
import com.jzx.provider.ucenter.consul.model.Consul;
import com.jzx.provider.ucenter.consul.repository.ConsulRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 人力顾问
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ConsulService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ConsulRepository consulRepository;

    @Autowired
    private ConsulOssService consulOssService;

    /**
     * 人力顾问信息的添加与修改
     *
     * @param consulCommand
     */
    public void saveOrUpdate(ConsulCommand consulCommand) {
        Consul consul = Consul.builder().build();
        BeanCopier.create(ConsulCommand.class, Consul.class, false)
                .copy(consulCommand, consul, null);
        consulRepository.save(consul);
    }

    /**
     * 注册
     */
    public void register(ConsulRegisterCommand consulRegisterCommand) {
        //验证码是否正确
        boolean exits = stringRedisTemplate.hasKey(consulRegisterCommand.getMobile() + "_" + consulRegisterCommand.getCode());
        if (!exits) {
            throw new UcenterRuntimeException(MyErrorType.CODE_NOT_EXITS);
        }
        Consul consul = consulRepository.findOne(Example.of(Consul.builder()
                .mobile(consulRegisterCommand.getMobile())
                .build())).orElse(null);
        if (consul != null) {
            throw new UcenterRuntimeException(MyErrorType.MOBILE_EXITS);
        }
        String salt = CodeUtil.salt();
        consul = Consul.builder()
                .salt(salt)
                .mobile(consulRegisterCommand.getMobile())
                .password(DigestUtils.md5DigestAsHex((salt + consulRegisterCommand.getPassword()).getBytes()))
                .status(1)
                .idCheck("0")
                .createTime(new Date())
                .updateTime(new Date())
                .build();
        consulRepository.save(consul);
    }

    /**
     * 登录
     */
    public ConsulResult login(ConsulLoginCommand loginCommand) {
        Consul consul = consulRepository.findOne(Example.of(Consul.builder()
                .mobile(loginCommand.getMobile())
                .build())).orElse(null);
        if (consul == null) {
            throw new UcenterRuntimeException(MyErrorType.MOBILE_NOT_EXITS);
        }
        //用户被禁用
        if (consul.getStatus().equals(Status.DISABLE.getValue())) {
            throw new UcenterRuntimeException(MyErrorType.USER_DISABLE);
        }
        if (!DigestUtils.md5DigestAsHex((consul.getSalt() + loginCommand.getPassword()).getBytes()).equals(consul.getPassword())) {
            throw new UcenterRuntimeException(MyErrorType.PASSWORD_ERROR);
        }
        String token = JwtUtil.genToken(ImmutableMap.of("id", consul.getId() + "", "time", System.currentTimeMillis() + ""));
        String key = PlatForm.CONSUL.getValue() + "_" + consul.getId() + "_login";
        stringRedisTemplate.opsForValue().set(key, token + "," + loginCommand.getMobile());
        //设置过期时间
        stringRedisTemplate.expire(key, Expire.USER, TimeUnit.MINUTES);
        ConsulResult consulResult = ConsulResult.builder().build();
        BeanCopier.create(Consul.class, ConsulResult.class, false).copy(consul, consulResult, null);
        consulResult.setToken(token);
        if (!StringUtils.isEmpty(consulResult.getHeadUrl())) {
            consulResult.setHeadUrl("http://consul.oss-cn-beijing.aliyuncs.com/" + consulResult.getHeadUrl());
        }
        return consulResult;
    }

    /**
     * 密码修改（忘记密码）
     */
    public void changePwd(ConsulChangePwdCommand changePwdCommand) {
        Consul consul = consulRepository.findOne(Example.of(Consul.builder()
                .mobile(changePwdCommand.getMobile())
                .build())).orElse(null);
        if (consul == null) {
            throw new UcenterRuntimeException(MyErrorType.MOBILE_NOT_EXITS);
        }
        //验证手机验证码
        boolean exits = stringRedisTemplate.hasKey(changePwdCommand.getMobile() + "_" + changePwdCommand.getCode());
        if (!exits) {
            throw new UcenterRuntimeException(MyErrorType.CODE_NOT_EXITS);
        }
        //修改密码
        String newPwd = DigestUtils.md5DigestAsHex((consul.getSalt() + changePwdCommand.getPassword()).getBytes());
        consul.setPassword(newPwd);
        consulRepository.save(consul);
    }

    public void changePwdByPwd(Integer id, ConsulChangePwdByPwdCommand consulChangePwdByPwdCommand) {
        Consul consul = consulRepository.findById(id).orElse(null);
        if (consul != null) {
            String oldPwd = DigestUtils.md5DigestAsHex((consul.getSalt() + consulChangePwdByPwdCommand.getOldPwd()).getBytes());
            if(!oldPwd.equals(consul.getPassword())){
                throw new UcenterRuntimeException(MyErrorType.PASSWORD_ERROR);
            }
            //修改密码
            String newPwd = DigestUtils.md5DigestAsHex((consul.getSalt() + consulChangePwdByPwdCommand.getNewPwd()).getBytes());
            consul.setPassword(newPwd);
            consulRepository.save(consul);
        }
    }

    /**
     * 给手机号发送验证码
     */
    public void sendCode(String mobile) {
        String code = "1234";//CodeUtil.mobileCode();
        //通过aliyun短信服务发送

        //将code存入到redis
        stringRedisTemplate.opsForValue().set(mobile + "_" + code, "");
        //设置过期时间
        stringRedisTemplate.expire(mobile + "_" + code, Expire.CODE, TimeUnit.MINUTES);
    }

    /**
     * 获取顾问详情
     *
     * @param id
     * @return
     */
    public ConsulResult findById(Integer id) {
        ConsulResult consulResult = ConsulResult.builder().build();
        consulRepository.findById(id).ifPresent(consul -> {
            BeanCopier.create(Consul.class, ConsulResult.class, false).copy(consul, consulResult, null);
        });
        consulResult.setHeadUrl("http://consul.oss-cn-beijing.aliyuncs.com/" + consulResult.getHeadUrl());
        return consulResult;
    }

    /**
     * 提交实名认证方法
     *
     * @param id                   consul的id
     * @param consulIdCheckCommand
     */
    public void checkIdCard(Integer id, ConsulIdCheckCommand consulIdCheckCommand) {
        Consul consul = consulRepository.findById(id).orElse(null);
        if (consul != null) {
            try {
                consulIdCheckCommand.setFrontPic(consulIdCheckCommand.getFrontPic().split(",")[1]);
                consulIdCheckCommand.setBackPic(consulIdCheckCommand.getBackPic().split(",")[1]);
                //将生成的base64码反编译回二进制字节码
                BASE64Decoder decoder = new BASE64Decoder();
                byte[] frontFile = decoder.decodeBuffer(consulIdCheckCommand.getFrontPic());
                ObjectMetadata objectMeta = new ObjectMetadata();
                objectMeta.setContentLength(frontFile.length);
                //将字节码转换成流
                InputStream input = new ByteArrayInputStream(frontFile);
                String frontUrl = "idcard/" + consul.getId() + "/" + consulIdCheckCommand.getIdno() + "_front.jpg";
                consulOssService.upLoad(input, frontUrl);

                byte[] backFile = decoder.decodeBuffer(consulIdCheckCommand.getBackPic());
                objectMeta.setContentLength(backFile.length);
                input = new ByteArrayInputStream(backFile);
                String backUrl = "idcard/" + consul.getId() + "/" + consulIdCheckCommand.getIdno() + "_back.jpg";
                consulOssService.upLoad(input, backUrl);
                consul.setName(consulIdCheckCommand.getName());
                consul.setIdCard(consulIdCheckCommand.getIdno());
                consul.setIdCardFrontUrl(frontUrl);
                consul.setIdCardBackUrl(backUrl);
                consul.setIdCheck("1");
                consulRepository.save(consul);
            } catch (Exception e) {
            }
        }
    }

    /**
     * 上传头像
     */
    public void uploadHead(Integer id, String base64Str) {
        Consul consul = consulRepository.findById(id).orElse(null);
        if (consul != null) {
            try {
                base64Str = base64Str.split(",")[1];
                //将生成的base64码反编译回二进制字节码
                BASE64Decoder decoder = new BASE64Decoder();
                byte[] file = decoder.decodeBuffer(base64Str);
                ObjectMetadata objectMeta = new ObjectMetadata();
                objectMeta.setContentLength(file.length);
                //将字节码转换成流
                InputStream input = new ByteArrayInputStream(file);
                String headUrl = "head/" + consul.getId() + "_head.jpg";
                consulOssService.upLoad(input, headUrl);
                consul.setHeadUrl(headUrl);
                consul.setUpdateTime(new Date());
                consulRepository.save(consul);
            } catch (Exception e) {
            }
        }
    }
}
